package io.github.junxworks.junx.stream.handler;

import io.github.junxworks.junx.stream.constants.DefaultParams;
import io.github.junxworks.junx.event.EventChannel;
import io.github.junxworks.junx.event.EventContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.Map;

/**
 * 异常处理类
 *
 * @author 王兴
 * @date 2024/09/10
 */
@Slf4j
public abstract class AbstractErrorHandler extends AbstractDataHandler {
    /**
     * @param event   当前事件上下文
     * @param channel 事件通道
     * @throws Exception
     */
    @Override
    public void handleEvent(EventContext event, EventChannel channel) throws Exception {
        incrCount();
        try {
            Object data = event.getData(DefaultParams.PARAM_DATA);
            Exception e = (Exception) event.getData(DefaultParams.PARAM_EXCEPTION);
            Map<String, Object> globalParams = (Map<String, Object>) event.getData(DefaultParams.PARAM_GLOBAL_PARAMS);
            if (data instanceof Collection) {
                for (Object d : (Collection) data) {
                    handleException(d, e, event, globalParams);
                }
            } else {
                handleException(data, e, event, globalParams);
            }
        } catch (Exception e) {
            log.error("管道数据异常处理异常", e);
        }finally {
            decrCount();
        }
    }

    public abstract void handleException(Object data, Exception e, EventContext context, Map<String, Object> globalParams);
}
